package cn.itcast.star.graph.core.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.itcast.star.graph.comfyui.client.pojo.ComfyuiModel;
import cn.itcast.star.graph.comfyui.client.pojo.ComfyuiRequestDto;
import cn.itcast.star.graph.comfyui.client.pojo.ComfyuiTask;
import cn.itcast.star.graph.core.dto.request.Text2ImageReqDto;
import cn.itcast.star.graph.core.service.FreemarkerService;
import cn.itcast.star.graph.core.service.OllamaServcie;
import cn.itcast.star.graph.core.service.Text2ImageService;
import freemarker.template.TemplateException;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;


@Service
public class Text2ImageServiceImpl implements Text2ImageService {

    private static final String COMFYUI_URL_ID = "star-graph";

    @Autowired
    private OllamaServcie ollamaServcie;

    @Autowired
    private FreemarkerService freemarkerService;

    public ComfyuiTask getComfyuiTask(Text2ImageReqDto text2ImageReqDto) throws TemplateException, IOException {
        // 1.将text2ImageReqDto转换成ComfyuiModel
        ComfyuiModel comfyuiModel = BeanUtil.toBean(text2ImageReqDto, ComfyuiModel.class);
        comfyuiModel.setWidth(text2ImageReqDto.width());
        comfyuiModel.setHeight(text2ImageReqDto.height());
        comfyuiModel.setModelName(text2ImageReqDto.modelName());
        comfyuiModel.setSamplerName(text2ImageReqDto.samplerName());
        comfyuiModel.setScheduler(text2ImageReqDto.scheduler());
        // 2.封装提示词与负面提示词
        comfyuiModel.setPrompt(String.format("(8k, best quality, masterpiece),(high detailed skin),%s",ollamaServcie.translate(comfyuiModel.getPrompt())));
        if (StringUtil.isNotEmpty(comfyuiModel.getReverse())) {
            comfyuiModel.setReverse(String.format("(lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry),%s",ollamaServcie.translate(comfyuiModel.getReverse())));
        }

        // 2.利用ComfyUIModel结合freemarker渲染出comfyui json
        String json = freemarkerService.renderText2Image(comfyuiModel);

        // 3.构建出comfyui生图需要的对象ComfyuiRequestDto
        ComfyuiRequestDto comfyuiRequestDto = new ComfyuiRequestDto(COMFYUI_URL_ID, json);

        // 4.构建出ComfyuiTask （Redis任务对象）
        return new ComfyuiTask(text2ImageReqDto.getClientId(), comfyuiRequestDto);
    }
}
